#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <onenet.h>
#include <wlan_mgnt.h>
#include <wlan_cfg.h>
#include <rtconfig.h>
#include <drv_lcd.h>

#define DBG_ENABLE
#define DBG_COLOR
#define DBG_SECTION_NAME    "onenet.sample"
#define KEY_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX / 2)

#define WIFI_SSID     "LZXS"
#define WIFI_PASSWORD "15944776783"

#if ONENET_DEBUG
#define DBG_LEVEL           DBG_LOG
#else
#define DBG_LEVEL           DBG_INFO
#endif /* ONENET_DEBUG */

#include <rtdbg.h>

#define PIN_LED_B              GET_PIN(F, 11)
#define PIN_LED_R              GET_PIN(F, 12)
#define PIN_BEEP               GET_PIN(B, 0)       // PB0 : 蜂鸣器

/* PWM控制LED亮度配置 */
#define PWM_DEV_NAME       "pwm1"
#define PWM_DEV_CHANNEL    4
#define LIGHT_MAX          1200.0f                // 最大光照阈值

/* 亮度等级定义（脉冲宽度ns） */
#define BRIGHT_LEVEL_0   50000      // 最暗（高光照）
#define BRIGHT_LEVEL_3   450000     // 最亮（低光照）

/* LCD显示配置 */
#define LCD_REFRESH_MS    1000      // LCD刷新间隔
#define FONT_SIZE         16        // 字体大小

// 显示位置定义
#define TITLE_X           10
#define VALUE_X           100
#define LINE_HEIGHT       20

// 行位置定义
#define LIGHT_LINE        10        // 10
#define TEMP_LINE         30        // 10+20
#define HUMI_LINE         50        // 30+20
#define FALL_LINE         70        // 50+20
#define TEMP_THRESH_LINE  90        // 70+20
#define HUMI_THRESH_LINE  110       // 90+20
#define WIFI_LINE         130       // 110+20
#define MODE_LINE         150       // 130+20
#define DEVICE_LINE       170       // 150+20 (设备状态起始行)
#define LCD_WIDTH          240

// 按键定义
#define PIN_BTN_LEFT     GET_PIN(C, 0)  // PC0
#define PIN_BTN_RIGHT    GET_PIN(C, 4)  // PC4
#define PIN_BTN_DOWN     GET_PIN(C, 1)  // PC1
#define PIN_BTN_UP       GET_PIN(C, 5)  // PC5

// 设备控制引脚
#define PIN_HUMIDIFIER   GET_PIN(E, 12) // PF10 - 加湿器控制
#define PIN_FAN          GET_PIN(E, 13) // PF13 - 风扇控制

// 系统模式定义
typedef enum {
    MODE_AUTO = 0,
    MODE_MANUAL
} SystemMode;

// 阈值选择定义
typedef enum {
    THRESH_TEMP = 0,
    THRESH_HUMI
} ThresholdType;

// 新增全局变量
static struct rt_device_pwm *pwm_dev = RT_NULL;
static rt_uint32_t pwm_period = 500000; // PWM周期0.5ms
static int fall_status = 0;  // 0表示正常，1表示摔倒

// 模式相关变量
static SystemMode current_mode = MODE_AUTO; // 默认自动模式
static ThresholdType selected_thresh = THRESH_TEMP; // 默认选择温度阈值
static rt_bool_t adjust_mode = RT_FALSE; // 是否处于阈值调整模式
static rt_bool_t blink_state = RT_FALSE; // 阈值闪烁状态
static rt_uint32_t last_blink_time = 0; // 上次闪烁时间
static rt_uint32_t blink_interval = 500; // 闪烁间隔(ms)

// 阈值变量
static rt_uint32_t temp_threshold = 35; // 温度阈值
static rt_uint32_t humi_threshold = 50; // 湿度阈值

// 设备状态变量
static rt_bool_t humidifier_state = RT_FALSE; // 加湿器状态
static rt_bool_t fan_state = RT_FALSE;       // 风扇状态
static rt_uint8_t brightness_level = 0;      // 亮度等级 (0-3)

#ifdef FINSH_USING_MSH
#include <finsh.h>

#include "aht10.h"
#include "ap3216c.h"

/* 提前声明函数 */
static void onenet_cmd_rsp_cb(uint8_t *recv_data, size_t recv_size, uint8_t **resp_data, size_t *resp_size);
static void auto_start_onenet(void);
static void update_lcd_display(void);

static struct rt_semaphore net_ready;
static rt_bool_t wifi_connected = RT_FALSE;
static rt_bool_t onenet_initialized = RT_FALSE;

// 设置阈值的函数
void set_temp_threshold(int threshold)
{
    if (threshold < 0) threshold = 0;
    if (threshold > 50) threshold = 50;

    temp_threshold = threshold;
    LOG_I("Set temperature threshold to %d by cloud", threshold);

    // 更新LCD显示
    update_lcd_display();
}

void set_humi_threshold(int threshold)
{
    if (threshold < 0) threshold = 0;
    if (threshold > 100) threshold = 100;

    humi_threshold = threshold;
    LOG_I("Set humidity threshold to %d by cloud", threshold);

    // 更新LCD显示
    update_lcd_display();
}

// 设置亮度等级函数
void set_brightness_level(int level)
{
    if (level < 0) level = 0;
    if (level > 3) level = 3;

    brightness_level = level;
    LOG_I("Set brightness level to %d by cloud", level);

    // 立即应用亮度设置
    if (pwm_dev)
    {
        rt_uint32_t pulse = 0;
        switch (brightness_level)
        {
            case 0: pulse = BRIGHT_LEVEL_0; break;
            case 1: pulse = (BRIGHT_LEVEL_0 + BRIGHT_LEVEL_3) / 3; break;
            case 2: pulse = (BRIGHT_LEVEL_0 + BRIGHT_LEVEL_3) * 2 / 3; break;
            case 3: pulse = BRIGHT_LEVEL_3; break;
        }
        rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, pwm_period, pulse);
    }

    // 如果当前在手动模式，更新显示
    if (current_mode == MODE_MANUAL)
    {
        update_lcd_display();
    }
}

// 风扇控制函数
void set_fan_state(rt_bool_t state)
{
    fan_state = state;
    rt_pin_write(PIN_FAN, state ? PIN_HIGH : PIN_LOW);
    LOG_I("Fan %s by cloud", state ? "ON" : "OFF");

    // 更新显示（如果当前在手动模式）
    if (current_mode == MODE_MANUAL)
    {
        update_lcd_display();
    }
}

// 加湿器控制函数
void set_humidifier_state(rt_bool_t state)
{
    humidifier_state = state;
    rt_pin_write(PIN_HUMIDIFIER, state ? PIN_HIGH : PIN_LOW);
    LOG_I("Humidifier %s by cloud", state ? "ON" : "OFF");

    // 更新显示（如果当前在手动模式）
    if (current_mode == MODE_MANUAL)
    {
        update_lcd_display();
    }
}
/* ==================== LCD显示功能 ==================== */
// 显示标题（固定文本）
static void lcd_show_titles(void)
{
    lcd_clear(WHITE);

    // 使用紧凑标题
    lcd_show_string(TITLE_X, LIGHT_LINE, FONT_SIZE, BLACK, "Light:");
    lcd_show_string(TITLE_X, TEMP_LINE, FONT_SIZE, BLACK, "Temp:");
    lcd_show_string(TITLE_X, HUMI_LINE, FONT_SIZE, BLACK, "Humi:");
    lcd_show_string(TITLE_X, FALL_LINE, FONT_SIZE, BLACK, "Fall:");
    lcd_show_string(TITLE_X, TEMP_THRESH_LINE, FONT_SIZE, BLACK, "Threshold:");
    lcd_show_string(TITLE_X, WIFI_LINE, FONT_SIZE, BLACK, "WiFi:");
    lcd_show_string(TITLE_X, MODE_LINE, FONT_SIZE, BLACK, "Mode:");

    // 显示初始阈值
    char thresh_str[16];
    rt_snprintf(thresh_str, sizeof(thresh_str), "T:%d H:%d", temp_threshold, humi_threshold);
    lcd_show_string(VALUE_X, TEMP_THRESH_LINE, FONT_SIZE, BLACK, "%s", thresh_str);

    // 显示初始模式
    lcd_show_string(VALUE_X, MODE_LINE, FONT_SIZE, BLACK, "AUTO");
}

/* ==================== 串口和蜂鸣器相关代码 ==================== */
#define UART_DEVICE_NAME     "uart3"      // 串口设备名称
static rt_device_t serial_dev;             // 串口设备句柄
static struct rt_semaphore uart_rx_sem;    // 串口接收信号量
static rt_thread_t beep_thread;            // 蜂鸣器控制线程

// 蜂鸣器控制线程入口函数
static void beep_thread_entry(void *parameter)
{
    uint32_t last_trigger_time = 0;
    const uint32_t MIN_INTERVAL = 5000; // 5秒内不重复触发

    while (1)
    {
        // 等待信号量触发
        rt_sem_take(&uart_rx_sem, RT_WAITING_FOREVER);

        uint32_t current_time = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);

        // 添加时间间隔检查，防止频繁触发
        if (last_trigger_time > 0 && current_time - last_trigger_time < MIN_INTERVAL)
        {
            LOG_W("Alarm ignored: too frequent (%d ms since last)",
                  current_time - last_trigger_time);
            continue;
        }

        // 触发蜂鸣器警报
        LOG_I("Alarm triggered! Buzzer ON");
        rt_pin_write(PIN_BEEP, PIN_HIGH);
        rt_thread_mdelay(1000);  // 蜂鸣器响1秒
        rt_pin_write(PIN_BEEP, PIN_LOW);
        LOG_I("Buzzer OFF");

        last_trigger_time = current_time;
    }
}

// 串口接收回调函数
static rt_err_t uart_rx_ind(rt_device_t dev, rt_size_t size)
{
    // 有数据到达，释放信号量
    rt_sem_release(&uart_rx_sem);
    return RT_EOK;
}

// 串口数据处理函数
static void uart_data_process(void)
{
    char ch;
    static uint32_t last_char_time = 0;
    const uint32_t DEBOUNCE_TIME = 100; // 100ms防抖

    // 尝试读取所有可用字符
    while (rt_device_read(serial_dev, 0, &ch, 1) == 1)
    {
        uint32_t current_time = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);

        // 添加防抖机制，防止连续字符
        if (last_char_time > 0 && current_time - last_char_time < DEBOUNCE_TIME) {
            LOG_D("Debounce: ignoring char '%c'", ch);
            continue;
        }
        last_char_time = current_time;

        // 处理接收到的字符
        if (ch == 'A' )
        {
            LOG_I("Received alarm command: '%c'", ch);
            rt_sem_release(&uart_rx_sem);  // 触发蜂鸣器

            // 设置摔倒状态为1
            fall_status = 1;
            LOG_I("Fall detected! Status set to 1");
        }
        else
        {
            LOG_D("Received char: '%c' (0x%02x)", ch, ch);
        }
    }
}

// 初始化串口和蜂鸣器
static int uart_beep_init(void)
{
    rt_err_t ret = RT_EOK;

    // 先强制关闭蜂鸣器
    rt_pin_mode(PIN_BEEP, PIN_MODE_OUTPUT);
    rt_pin_write(PIN_BEEP, PIN_LOW);
    LOG_I("Buzzer initialized and set to OFF");

    // 初始化信号量
    rt_sem_init(&uart_rx_sem, "uart_rx", 0, RT_IPC_FLAG_FIFO);

    // 查找串口设备
    serial_dev = rt_device_find(UART_DEVICE_NAME);
    if (!serial_dev)
    {
        LOG_E("UART device %s not found!", UART_DEVICE_NAME);
        return -RT_ERROR;
    }

    // 打开串口设备 (中断接收模式)
    ret = rt_device_open(serial_dev, RT_DEVICE_FLAG_INT_RX);
    if (ret != RT_EOK)
    {
        LOG_E("Failed to open UART device: %d", ret);
        return ret;
    }

    // 配置串口参数 (115200, 8N1)
    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
    config.baud_rate = BAUD_RATE_115200;
    config.data_bits = DATA_BITS_8;
    config.stop_bits = STOP_BITS_1;
    config.parity    = PARITY_NONE;

    rt_device_control(serial_dev, RT_DEVICE_CTRL_CONFIG, &config);

    // 设置接收回调函数
    rt_device_set_rx_indicate(serial_dev, uart_rx_ind);

    // 创建并启动蜂鸣器控制线程
    beep_thread = rt_thread_create("beep_ctrl",
                                 beep_thread_entry,
                                 RT_NULL,
                                 512,
                                 RT_THREAD_PRIORITY_MAX / 3,
                                 10);
    if (beep_thread)
    {
        rt_thread_startup(beep_thread);
        LOG_I("UART and buzzer initialized. Waiting for 'A' command...");
    }
    else
    {
        LOG_E("Failed to create beep control thread!");
        return -RT_ERROR;
    }

    return RT_EOK;
}
/* ==================== 结束 ==================== */

// 根据光照强度计算亮度等级
static rt_uint32_t calculate_brightness(float light)
{
    // 标准化光照值到0-100%范围
    float normalized = light / LIGHT_MAX;
    if(normalized > 1.0f) normalized = 1.0f;
    if(normalized < 0.0f) normalized = 0.0f;

    // 反转值（光照越强，LED越暗）
    float brightness = 1.0f - normalized;

    // 根据当前亮度等级调整
    if (current_mode == MODE_MANUAL)
    {
            // 手动模式下直接根据亮度等级设置
            switch (brightness_level)
            {
                case 0: return BRIGHT_LEVEL_0;      // 最暗
                case 1: return (BRIGHT_LEVEL_0 + BRIGHT_LEVEL_3) * 0.33f;
                case 2: return (BRIGHT_LEVEL_0 + BRIGHT_LEVEL_3) * 0.66f;
                case 3: return BRIGHT_LEVEL_3;      // 最亮
                default: return BRIGHT_LEVEL_0;
            }
    }

    // 映射到PWM脉冲范围 (50000-450000ns)
    return BRIGHT_LEVEL_0 + (rt_uint32_t)(brightness * (BRIGHT_LEVEL_3 - BRIGHT_LEVEL_0));
}

// WiFi状态变化处理函数
static void wifi_status_handler(int event, struct rt_wlan_buff *buff, void *parameter)
{
    switch (event)
    {
        case RT_WLAN_EVT_STA_CONNECTED:
            LOG_I("WiFi connected to AP");
            wifi_connected = RT_TRUE;
            rt_sem_release(&net_ready);

            // 更新WiFi状态显示
            lcd_fill(VALUE_X, WIFI_LINE, LCD_WIDTH, WIFI_LINE + FONT_SIZE, WHITE);
            lcd_show_string(VALUE_X, WIFI_LINE, FONT_SIZE, GREEN, "Connected");
            break;

        case RT_WLAN_EVT_STA_DISCONNECTED:
            LOG_W("WiFi disconnected");
            wifi_connected = RT_FALSE;

            // 更新WiFi状态显示
            lcd_fill(VALUE_X, WIFI_LINE, LCD_WIDTH, WIFI_LINE + FONT_SIZE, WHITE);
            lcd_show_string(VALUE_X, WIFI_LINE, FONT_SIZE, RED, "Disconnected");
            break;

        case RT_WLAN_EVT_STA_CONNECTED_FAIL:
            LOG_E("WiFi connection failed");

            // 更新WiFi状态显示
            lcd_fill(VALUE_X, WIFI_LINE, LCD_WIDTH, WIFI_LINE + FONT_SIZE, WHITE);
            lcd_show_string(VALUE_X, WIFI_LINE, FONT_SIZE, RED, "Failed");
            break;
    }
}

// WiFi自动连接函数
static int wifi_auto_connect(void)
{
    rt_err_t result = RT_EOK;

    // 初始化网络就绪信号量
    if (rt_sem_init(&net_ready, "net_ready", 0, RT_IPC_FLAG_FIFO) != RT_EOK)
    {
        LOG_E("Failed to create net_ready semaphore");
        return -RT_ERROR;
    }

    // 注册WiFi事件处理函数
    rt_wlan_register_event_handler(RT_WLAN_EVT_STA_CONNECTED, wifi_status_handler, RT_NULL);
    rt_wlan_register_event_handler(RT_WLAN_EVT_STA_CONNECTED_FAIL, wifi_status_handler, RT_NULL);
    rt_wlan_register_event_handler(RT_WLAN_EVT_STA_DISCONNECTED, wifi_status_handler, RT_NULL);

    // 检查是否已经连接
    if (rt_wlan_is_connected())
    {
        LOG_I("Already connected to WiFi");
        wifi_connected = RT_TRUE;
        rt_sem_release(&net_ready);
        return RT_EOK;
    }

    // 设置工作模式为station模式
    if (rt_wlan_set_mode(RT_WLAN_DEVICE_STA_NAME, RT_WLAN_STATION) != RT_EOK)
    {
        LOG_E("Failed to set WiFi mode");
        return -RT_ERROR;
    }

    // 配置自动重连
    rt_wlan_config_autoreconnect(RT_TRUE);

    // 连接热点
    LOG_I("Connecting to WiFi: %s", WIFI_SSID);
    result = rt_wlan_connect(WIFI_SSID, WIFI_PASSWORD);

    if (result == RT_EOK)
    {
        LOG_I("WiFi connection initiated, waiting for connection...");

        // 更新WiFi状态显示
        lcd_fill(VALUE_X, WIFI_LINE, LCD_WIDTH, WIFI_LINE + FONT_SIZE, WHITE);
        lcd_show_string(VALUE_X, WIFI_LINE, FONT_SIZE, BLACK, "Connecting");

        // 等待网络就绪（60秒超时）
        if (rt_sem_take(&net_ready, rt_tick_from_millisecond(60000)) == RT_EOK)
        {
            LOG_I("WiFi connected successfully!");
            return RT_EOK;
        }
        else
        {
            LOG_E("WiFi connection timeout!");
            return -RT_ETIMEOUT;
        }
    }
    else
    {
        LOG_E("WiFi connect failed! Error: %d", result);
        return result;
    }
}

// OneNET初始化函数
static int onenet_auto_init(void)
{
    if (onenet_initialized)
    {
        LOG_W("OneNET already initialized");
        return 0;
    }

    LOG_I("Initializing OneNET MQTT...");

    // 确保网络已连接
    if (!wifi_connected)
    {
        LOG_E("Cannot initialize OneNET: WiFi not connected");
        return -1;
    }

    int ret = onenet_mqtt_init();

    if (ret < 0)
    {
        LOG_E("OneNET MQTT initialize failed! Error: %d", ret);
        return -1;
    }

    LOG_I("OneNET MQTT initialize success!");
    onenet_initialized = RT_TRUE;

    // 设置命令响应回调
    rt_pin_mode(PIN_LED_B, PIN_MODE_OUTPUT);
    rt_pin_mode(PIN_LED_R, PIN_MODE_OUTPUT);
    onenet_set_cmd_rsp_cb(onenet_cmd_rsp_cb);
    LOG_I("OneNET command response callback set");

    return 0;
}

/* ==================== 按键处理功能 ==================== */
static void key_scan_thread_entry(void *parameter);
static void handle_auto_mode_keys(void);
static void handle_manual_mode_keys(void);
static void update_lcd_display(void);
static void toggle_blink_state(void);

// 按键扫描线程
static void key_scan_thread_entry(void *parameter)
{
    while (1) {
        // 模式切换键 (GPIO_BTN_LEFT)
        if (rt_pin_read(PIN_BTN_LEFT) == PIN_LOW)
        {
            rt_thread_mdelay(50); // 消抖
            if (rt_pin_read(PIN_BTN_LEFT) == PIN_LOW)
            {
                // 切换模式
                current_mode = (current_mode == MODE_AUTO) ? MODE_MANUAL : MODE_AUTO;
                adjust_mode = RT_FALSE; // 退出调整模式
                LOG_I("Switched to %s mode", current_mode == MODE_AUTO ? "AUTO" : "MANUAL");

                // 等待按键释放
                while (rt_pin_read(PIN_BTN_LEFT) == PIN_LOW)
                {
                    rt_thread_mdelay(10);
                }
            }
            update_lcd_display();
        }

        // 处理其他按键
        if (current_mode == MODE_AUTO)
        {
            handle_auto_mode_keys();
        }
        else
        {
            handle_manual_mode_keys();
        }

        // 更新闪烁状态
        rt_uint32_t current_time = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);
        if (adjust_mode && (current_time - last_blink_time >= blink_interval))
        {
            toggle_blink_state();
            last_blink_time = current_time;
        }

        rt_thread_mdelay(10);
    }
}

// 自动模式按键处理
static void handle_auto_mode_keys(void)
{
    static rt_bool_t right_key_handled = RT_FALSE;
    const rt_uint32_t long_press_time = 1000; // 长按判定时间(ms)
    static rt_uint32_t last_key_time = 0;
    rt_uint32_t key_start_time = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);
       // GPIO_BTN_RIGHT处理
       if (rt_pin_read(PIN_BTN_RIGHT) == PIN_LOW)
       {
           rt_uint32_t press_start = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);
           rt_bool_t is_long_press = RT_FALSE;
           right_key_handled = RT_FALSE;

           // 等待按键释放或长按
           while (rt_pin_read(PIN_BTN_RIGHT) == PIN_LOW)
           {
               rt_thread_mdelay(10);
               rt_uint32_t current_time = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);

               // 长按处理
               if (!right_key_handled && (current_time - press_start) >= long_press_time)
               {
                   adjust_mode = RT_TRUE;
                   LOG_I("Enter threshold adjustment mode");
                   is_long_press = RT_TRUE;
                   right_key_handled = RT_TRUE;
                   update_lcd_display(); // 立即更新显示
               }
           }

           // 短按处理 (按键已释放且未处理过长按)
           if (!is_long_press && !right_key_handled)
           {
               // 切换选择的阈值类型
               selected_thresh = (selected_thresh == THRESH_TEMP) ? THRESH_HUMI : THRESH_TEMP;
               LOG_I("Selected threshold: %s", selected_thresh == THRESH_TEMP ? "TEMP" : "HUMI");
               right_key_handled = RT_TRUE;
               update_lcd_display(); // 立即更新显示
           }
       }
       else
       {
           right_key_handled = RT_FALSE;
       }
    // GPIO_BTN_UP处理 (增加阈值)
    if (adjust_mode && rt_pin_read(PIN_BTN_UP) == PIN_LOW)
    {
        rt_thread_mdelay(50); // 消抖
        if (rt_pin_read(PIN_BTN_UP) == PIN_LOW)
        {
            if (selected_thresh == THRESH_TEMP)
            {
                temp_threshold++;
                LOG_I("Temperature threshold increased to: %d", temp_threshold);
            }
            else
            {
                humi_threshold++;
                LOG_I("Humidity threshold increased to: %d", humi_threshold);
            }

            // 等待按键释放
            while (rt_pin_read(PIN_BTN_UP) == PIN_LOW)
            {
                rt_thread_mdelay(10);
            }
            update_lcd_display();
      }
    }

    // GPIO_BTN_DOWN处理 (减少阈值)
    if (adjust_mode && rt_pin_read(PIN_BTN_DOWN) == PIN_LOW)
    {
        rt_thread_mdelay(50); // 消抖
        if (rt_pin_read(PIN_BTN_DOWN) == PIN_LOW)
        {
            if (selected_thresh == THRESH_TEMP)
            {
                if (temp_threshold > 0) temp_threshold--;
                LOG_I("Temperature threshold decreased to: %d", temp_threshold);
            }
            else
            {
                if (humi_threshold > 0) humi_threshold--;
                LOG_I("Humidity threshold decreased to: %d", humi_threshold);
            }

            // 等待按键释放
            while (rt_pin_read(PIN_BTN_DOWN) == PIN_LOW)
            {
                rt_thread_mdelay(10);
            }
            update_lcd_display();
        }

    }
    if (last_key_time > 0)
    {
        rt_uint32_t current_time = rt_tick_get() * (1000 / RT_TICK_PER_SECOND);
        LOG_D("Key response time: %d ms", current_time - key_start_time);
    }
        last_key_time = key_start_time;
}

// 手动模式按键处理
static void handle_manual_mode_keys(void)
{
    // GPIO_BTN_UP处理 (切换灯亮度)
    if (rt_pin_read(PIN_BTN_UP) == PIN_LOW)
    {
        rt_thread_mdelay(50);
        if (rt_pin_read(PIN_BTN_UP) == PIN_LOW)
        {
            int next_level = (brightness_level + 1) % 4;
            set_brightness_level(next_level);

            // 等待按键释放
            while (rt_pin_read(PIN_BTN_UP) == PIN_LOW)
            {
                rt_thread_mdelay(10);
            }
        }
    }

    // GPIO_BTN_DOWN处理 (开关加湿器)
    if (rt_pin_read(PIN_BTN_DOWN) == PIN_LOW)
    {
        rt_thread_mdelay(50);
        if (rt_pin_read(PIN_BTN_DOWN) == PIN_LOW)
        {
            humidifier_state = !humidifier_state;
            rt_pin_write(PIN_HUMIDIFIER, humidifier_state ? PIN_HIGH : PIN_LOW);
            LOG_I("Humidifier %s", humidifier_state ? "ON" : "OFF");

            // 等待按键释放
            while (rt_pin_read(PIN_BTN_DOWN) == PIN_LOW)
            {
                rt_thread_mdelay(10);
            }
            update_lcd_display(); // 立即更新显示
        }
    }

    // GPIO_BTN_RIGHT处理 (开关风扇)
    if (rt_pin_read(PIN_BTN_RIGHT) == PIN_LOW)
    {
        rt_thread_mdelay(50);
        if (rt_pin_read(PIN_BTN_RIGHT) == PIN_LOW)
        {
            fan_state = !fan_state;
            rt_pin_write(PIN_FAN, fan_state ? PIN_HIGH : PIN_LOW);
            LOG_I("Fan %s", fan_state ? "ON" : "OFF");

            // 等待按键释放
            while (rt_pin_read(PIN_BTN_RIGHT) == PIN_LOW)
            {
                rt_thread_mdelay(10);
            }
            update_lcd_display(); // 立即更新显示
        }
    }
}

// 切换阈值闪烁状态
static void toggle_blink_state(void)
{
    blink_state = !blink_state;
}

// 更新LCD显示
static void update_lcd_display(void)
{
   static uint32_t last_update = 0;
   uint32_t now = rt_tick_get();

   // 限制刷新频率（最少200ms刷新一次）
   if (now - last_update < rt_tick_from_millisecond(200))
   {
       return;
   }
   last_update = now;
    // 清除模式行区域
    lcd_fill(VALUE_X, MODE_LINE, LCD_WIDTH, MODE_LINE + FONT_SIZE, WHITE);

    // 显示当前模式
    lcd_show_string(VALUE_X, MODE_LINE, FONT_SIZE,
                   current_mode == MODE_AUTO ? GREEN : BLUE,
                   "%s", current_mode == MODE_AUTO ? "AUTO" : "MANUAL");
    lcd_fill(VALUE_X, TEMP_THRESH_LINE, LCD_WIDTH, HUMI_THRESH_LINE + FONT_SIZE, WHITE);
    // 显示阈值
    char temp_str[16], humi_str[16];
    rt_snprintf(temp_str, sizeof(temp_str), "%d", temp_threshold);
    rt_snprintf(humi_str, sizeof(humi_str), "%d", humi_threshold);

    // 使用颜色区分选中状态
    if (adjust_mode)
    {
        // 调整模式下，被选中的阈值用蓝色显示
        if (selected_thresh == THRESH_TEMP)
        {
            lcd_show_string(VALUE_X, TEMP_THRESH_LINE, FONT_SIZE, BLUE, "%s", temp_str);
            lcd_show_string(VALUE_X, HUMI_THRESH_LINE, FONT_SIZE, BLACK, "%s", humi_str);
        }
        else
        {
            lcd_show_string(VALUE_X, TEMP_THRESH_LINE, FONT_SIZE, BLACK, "%s", temp_str);
            lcd_show_string(VALUE_X, HUMI_THRESH_LINE, FONT_SIZE, BLUE, "%s", humi_str);
        }
    }
    else
    {
        // 非调整模式，都显示黑色
        lcd_show_string(VALUE_X, TEMP_THRESH_LINE, FONT_SIZE, BLACK, "%s", temp_str);
        lcd_show_string(VALUE_X, HUMI_THRESH_LINE, FONT_SIZE, BLACK, "%s", humi_str);
    }

    // 手动模式下显示设备状态
    if (current_mode == MODE_MANUAL)
    {
        lcd_fill(TITLE_X, DEVICE_LINE, LCD_WIDTH, DEVICE_LINE + FONT_SIZE, WHITE);

        char device_str[48];
        rt_snprintf(device_str, sizeof(device_str), "Humi:%s Fan:%s Br:Lv%d",
                          rt_pin_read(PIN_HUMIDIFIER) ? "ON" : "OFF",  // 直接读取GPIO状态
                          rt_pin_read(PIN_FAN) ? "ON" : "OFF",         // 直接读取GPIO状态
                          brightness_level);

        lcd_show_string(TITLE_X, DEVICE_LINE, FONT_SIZE, BLACK, "%s", device_str);
    }
    else
    {
        // 自动模式下清除设备状态显示区域
        lcd_fill(TITLE_X, DEVICE_LINE, LCD_WIDTH, DEVICE_LINE + FONT_SIZE, WHITE);
    }
}

static void onenet_upload_entry(void *parameter)
{
    LOG_I("OneNET upload thread started");

   // 等待WiFi连接就绪
   while (!wifi_connected)
   {
       LOG_I("Waiting for WiFi connection...");
       rt_thread_mdelay(1000);
   }

   LOG_I("WiFi connected, initializing sensors...");

   // 添加启动延迟，防止开机误触发
   LOG_I("Delaying 3 seconds to prevent false alarms...");
   rt_thread_mdelay(3000);

   float humidity, temperature, brightness;
   char temp_str[16];
   char humi_str[16];
   char bright_str[16];

   aht10_device_t dev1 = RT_NULL;
   ap3216c_device_t dev2 = RT_NULL;

   /* 总线名称 */
   const char *i2c_bus_name1 = "i2c2";
   const char *i2c_bus_name2 = "i2c3";

   /* 初始化 ap3216c */
   dev2 = ap3216c_init(i2c_bus_name1);
   if (dev2 == RT_NULL)
   {
       LOG_E("ap3216c initializes failure.");
       lcd_show_string(10, 220, FONT_SIZE, RED, "AP3216C Init Failed!");
   }
   else
   {
       LOG_I("ap3216c initialized successfully");
   }

   /* 等待传感器正常工作 */
   rt_thread_mdelay(2000);

   /* 初始化 aht10 */
   dev1 = aht10_init(i2c_bus_name2);
   if (dev1 == RT_NULL)
   {
       LOG_E("aht10 initializes failure");
       lcd_show_string(10, 250, FONT_SIZE, RED, "AHT10 Init Failed!");
   }
   else
   {
       LOG_I("aht10 initialized successfully");
   }

   if (dev1 == RT_NULL || dev2 == RT_NULL)
   {
       LOG_E("Sensor initialization failed, stopping upload thread");
       return;
   }

   /* 初始化PWM设备 */
   pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
   if (!pwm_dev)
   {
       LOG_E("PWM Device Not Found");
       lcd_show_string(10, 280, FONT_SIZE, RED, "PWM Init Failed!");
   }
   else
   {
       rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, pwm_period, 0);
       rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);
       LOG_I("PWM initialized successfully");
   }

   while (1)
   {
       // 检查网络连接
       if (!wifi_connected)
       {
           LOG_W("WiFi disconnected, attempting to reconnect...");
           wifi_auto_connect();  // 主动尝试重连

           // 等待重新连接
           while (!wifi_connected)
           {
               rt_thread_mdelay(1000);
           }

           // 重新初始化OneNET
           if (onenet_auto_init() != RT_EOK) {
               LOG_E("OneNET reinitialization failed!");
           } else {
               LOG_I("OneNET reinitialized successfully");
           }
       }

       // 读取传感器数据
       temperature = aht10_read_temperature(dev1);
       humidity = aht10_read_humidity(dev1);
       brightness = ap3216c_read_ambient_light(dev2);

       // 使用整数方式打印浮点数
       int temp_int = (int)temperature;
       int temp_frac = (int)((temperature - temp_int) * 100);
       int humi_int = (int)humidity;
       int humi_frac = (int)((humidity - humi_int) * 100);
       int bright_int = (int)brightness;
       int bright_frac = (int)((brightness - bright_int) * 100);

       LOG_D("Raw sensor readings - Temp: %d.%02d, Humi: %d.%02d, Bright: %d.%02d",
             temp_int, temp_frac, humi_int, humi_frac, bright_int, bright_frac);

       // 四舍五入到两位小数
       temperature = (float)((int)(temperature * 100 + 0.5) / 100.0);
       humidity = (float)((int)(humidity * 100 + 0.5) / 100.0);
       brightness = (float)((int)(brightness * 100 + 0.5) / 100.0);

       // 手动分离整数和小数部分
       temp_int = (int)temperature;
       temp_frac = (int)((temperature - temp_int) * 100);

       humi_int = (int)humidity;
       humi_frac = (int)((humidity - humi_int) * 100);

       bright_int = (int)brightness;
       bright_frac = (int)((brightness - bright_int) * 100);

       // 构造字符串
       rt_snprintf(temp_str, sizeof(temp_str), "%d.%02d", temp_int, temp_frac);
       rt_snprintf(humi_str, sizeof(humi_str), "%d.%02d", humi_int, humi_frac);
       rt_snprintf(bright_str, sizeof(bright_str), "%d.%02d", bright_int, bright_frac);

       LOG_D("Formatted data - Temp: %s, Humi: %s, Bright: %s", temp_str, humi_str, bright_str);

       // 使用字符串上传
       LOG_I("Uploading temperature: %s", temp_str);
       if (onenet_mqtt_upload_string("temperature", temp_str) < 0)
       {
           LOG_E("Temperature upload failed!");
       }
       else
       {
           lcd_fill(VALUE_X, TEMP_LINE, LCD_WIDTH, TEMP_LINE + FONT_SIZE, WHITE);
          // 仅自动模式执行阈值控制
          if (current_mode == MODE_AUTO)
          {
              if (temperature > temp_threshold)
              {
                  lcd_show_string(VALUE_X, TEMP_LINE, FONT_SIZE, RED, "T:%s", temp_str);
                  rt_pin_write(PIN_FAN, PIN_HIGH);
              }
              else
              {
                  lcd_show_string(VALUE_X, TEMP_LINE, FONT_SIZE, BLACK, "T:%s", temp_str);
                  rt_pin_write(PIN_FAN, PIN_LOW);
              }
          }
          else // 手动模式只显示不控制
          {
              lcd_show_string(VALUE_X, TEMP_LINE, FONT_SIZE, BLACK, "T:%s", temp_str);
          }
          LOG_D("Temperature uploaded successfully");
       }

       rt_thread_mdelay(500);

       LOG_I("Uploading humidity: %s", humi_str);
       if (onenet_mqtt_upload_string("humidity", humi_str) < 0)
       {
           LOG_E("Humidity upload failed!");
       }
       else
       {
          lcd_fill(VALUE_X, HUMI_LINE, LCD_WIDTH, HUMI_LINE + FONT_SIZE, WHITE);
          // 仅自动模式执行阈值控制
          if (current_mode == MODE_AUTO)
          {
              if (humidity < humi_threshold)
              {
                  lcd_show_string(VALUE_X, HUMI_LINE, FONT_SIZE, RED, "H:%s", humi_str);
                  rt_pin_write(PIN_HUMIDIFIER, PIN_HIGH);
              }
              else
              {
                  lcd_show_string(VALUE_X, HUMI_LINE, FONT_SIZE, BLACK, "H:%s", humi_str);
                  rt_pin_write(PIN_HUMIDIFIER, PIN_LOW);
              }
          }
          else // 手动模式只显示不控制
          {
              lcd_show_string(VALUE_X, HUMI_LINE, FONT_SIZE, BLACK, "H:%s", humi_str);
          }
          LOG_D("Humidity uploaded successfully");
       }

       rt_thread_mdelay(500);

       LOG_I("Uploading brightness: %s", bright_str);
       if (onenet_mqtt_upload_string("brightness", bright_str) < 0)
       {
           LOG_E("Brightness upload failed!");
       }
       else
       {
           lcd_fill(VALUE_X, LIGHT_LINE, LCD_WIDTH, LIGHT_LINE + FONT_SIZE, WHITE);
           lcd_show_string(VALUE_X, LIGHT_LINE, FONT_SIZE, BLACK, "L:%s", bright_str);
           LOG_D("Brightness uploaded successfully");
       }

       // 上传摔倒检测状态
       LOG_I("Uploading fall detection: %d", fall_status);
       if (onenet_mqtt_upload_digit("shuaidao", fall_status) < 0)
       {
           LOG_E("Fall detection upload failed!");
       }
       else
       {
           const char *status_str = fall_status ? "FALL!" : "Normal";
           lcd_fill(VALUE_X, FALL_LINE, VALUE_X + 120, FALL_LINE + FONT_SIZE, WHITE);
           lcd_show_string(VALUE_X, FALL_LINE, FONT_SIZE, fall_status ? RED : BLACK, "%s", status_str);
       }

       // 重置摔倒状态为0（正常状态）
       fall_status = 0;

       /* 根据光照强度控制LED亮度 */
       if (pwm_dev)
       {
           rt_uint32_t pulse = calculate_brightness(brightness);

           // 确保脉冲值在有效范围内
           if(pulse < BRIGHT_LEVEL_0) pulse = BRIGHT_LEVEL_0;
           if(pulse > BRIGHT_LEVEL_3) pulse = BRIGHT_LEVEL_3;

           // 设置PWM输出
           rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, pwm_period, pulse);

           // 修复日志显示：使用整数和小数部分
           int brightness_int = (int)brightness;
           int brightness_frac = (int)((brightness - brightness_int) * 100);
           LOG_I("Set PWM: period=%dns, pulse=%dns for brightness=%d.%02d",
                 pwm_period, pulse, brightness_int, brightness_frac);
       }

       /* 处理串口数据 */
       uart_data_process();

       /* 更新LCD显示 */
       update_lcd_display();

       LOG_I("Upload cycle completed, waiting for next cycle...");
       rt_thread_delay(rt_tick_from_millisecond(5 * 1000));
   }
}

// 自动启动OneNET上传任务
static void auto_start_onenet(void)
{
    LOG_I("Starting OneNET auto upload...");

    // 确保WiFi已连接
    if (!wifi_connected) {
        LOG_E("Cannot start OneNET: WiFi not connected");
        return;
    }

    // 初始化OneNET
    if (onenet_auto_init() != 0)
    {
        LOG_E("OneNET initialization failed, retrying in 5 seconds...");
        rt_thread_mdelay(5000);

        // 重试初始化
        if (onenet_auto_init() != 0)
        {
            LOG_E("OneNET initialization failed after retry, giving up");
            return;
        }
    }

    // 创建并启动上传线程
    rt_thread_t tid = rt_thread_create("onenet_auto",
                           onenet_upload_entry,
                           RT_NULL,
                           3 * 1024,
                           RT_THREAD_PRIORITY_MAX / 3 - 1,
                           5);
    if (tid)
    {
        rt_thread_startup(tid);
        LOG_I("OneNET auto upload started!");
    }
    else
    {
        LOG_E("Failed to create OneNET upload thread!");
    }
}
// 自动连接初始化
static int auto_connect_init(void)
{
    LOG_I("Starting auto connection sequence...");

    // 重置状态标志
    wifi_connected = RT_FALSE;
    onenet_initialized = RT_FALSE;

    // 初始化WiFi连接
    wifi_auto_connect();

    return 0;
}
INIT_APP_EXPORT(auto_connect_init);

static void onenet_cmd_rsp_cb(uint8_t *recv_data, size_t recv_size, uint8_t **resp_data, size_t *resp_size)
{
    char res_buf[] = { "cmd is received!\n" };

    LOG_D("Received command: %x:%x", recv_data[0], recv_data[1]);

    if(recv_data[0] == 0x00)
    {
        rt_pin_write(PIN_LED_B, recv_data[1] > 0 ? PIN_HIGH : PIN_LOW);
        LOG_I("Blue light %s", recv_data[1] > 0 ? "ON" : "OFF");
    }
    else if(recv_data[0] == 0x01)
    {
        rt_pin_write(PIN_LED_R, recv_data[1] > 0 ? PIN_HIGH : PIN_LOW);
        LOG_I("Red light %s", recv_data[1] > 0 ? "ON" : "OFF");
    }

    *resp_data = (uint8_t *) ONENET_MALLOC(strlen(res_buf));
    if (*resp_data == RT_NULL)
    {
        LOG_E("Failed to allocate memory for response");
        *resp_size = 0;
        return;
    }

    rt_strncpy((char *)*resp_data, res_buf, strlen(res_buf));
    *resp_size = strlen(res_buf);
}

int onenet_upload_cycle(void)
{
    auto_start_onenet();
    return 0;
}
MSH_CMD_EXPORT(onenet_upload_cycle, send data to OneNET cloud cycle);

int onenet_publish_digit(int argc, char **argv)
{
    if (argc != 3)
    {
        LOG_E("onenet_publish [datastream_id]  [value]  - mqtt pulish digit data to OneNET.");
        return -1;
    }

    int ret = onenet_mqtt_upload_digit(argv[1], atoi(argv[2]));
    if (ret < 0)
    {
        LOG_E("Upload digit data failed! Error: %d", ret);
    }
    else
    {
        LOG_I("Digit data uploaded successfully");
    }

    return ret;
}
MSH_CMD_EXPORT_ALIAS(onenet_publish_digit, onenet_mqtt_publish_digit, send digit data to onenet cloud);

int onenet_publish_string(int argc, char **argv)
{
    if (argc != 3)
    {
        LOG_E("onenet_publish [datastream_id]  [string]  - mqtt pulish string data to OneNET.");
        return -1;
    }

    int ret = onenet_mqtt_upload_string(argv[1], argv[2]);
    if (ret < 0)
    {
        LOG_E("Upload string data failed! Error: %d", ret);
    }
    else
    {
        LOG_I("String data uploaded successfully");
    }

    return ret;
}
MSH_CMD_EXPORT_ALIAS(onenet_publish_string, onenet_mqtt_publish_string, send string data to onenet cloud);

int onenet_set_cmd_rsp(int argc, char **argv)
{
    rt_pin_mode(PIN_LED_B, PIN_MODE_OUTPUT);
    rt_pin_mode(PIN_LED_R, PIN_MODE_OUTPUT);
    onenet_set_cmd_rsp_cb(onenet_cmd_rsp_cb);
    LOG_I("OneNET command response callback set");
    return 0;
}
MSH_CMD_EXPORT(onenet_set_cmd_rsp, set cmd response function);

#endif /* FINSH_USING_MSH */

int main(void)
{
    LOG_I("Main thread started");

    /* 初始化LCD */
    lcd_clear(WHITE);
    lcd_show_titles();
    LOG_I("LCD initialized with titles");

    /* 先确保蜂鸣器关闭 */
    rt_pin_mode(PIN_BEEP, PIN_MODE_OUTPUT);
    rt_pin_write(PIN_BEEP, PIN_LOW);  // 强制关闭蜂鸣器

    /* 初始化设备控制引脚 */
    rt_pin_mode(PIN_HUMIDIFIER, PIN_MODE_OUTPUT);
    rt_pin_mode(PIN_FAN, PIN_MODE_OUTPUT);
    rt_pin_write(PIN_HUMIDIFIER, PIN_LOW); // 初始关闭
    rt_pin_write(PIN_FAN, PIN_LOW);        // 初始关闭

    /* 初始化按键引脚 */
    rt_pin_mode(PIN_BTN_LEFT, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(PIN_BTN_RIGHT, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(PIN_BTN_DOWN, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(PIN_BTN_UP, PIN_MODE_INPUT_PULLUP);

    /* 显示初始WiFi状态 */
    lcd_fill(VALUE_X, WIFI_LINE, LCD_WIDTH, WIFI_LINE + FONT_SIZE, WHITE);
    lcd_show_string(VALUE_X, WIFI_LINE, FONT_SIZE, BLACK, "Initializing");

    /* 等待网络连接就绪 */
    LOG_I("Waiting for network connection...");
    while (!wifi_connected)
    {
        rt_thread_mdelay(500);
        LOG_I("Waiting for WiFi...");
    }

    LOG_I("Network connected, initializing peripherals...");

    /* 初始化串口和蜂鸣器 */
    uart_beep_init();

    /* 创建按键扫描线程 */
    rt_thread_t key_thread = rt_thread_create("key_scan",
                                            key_scan_thread_entry,
                                            RT_NULL,
                                            1024,
                                            KEY_THREAD_PRIORITY,
                                            10);
    if (key_thread != RT_NULL) {
        rt_thread_startup(key_thread);
        LOG_I("Key scan thread started");
    } else {
        LOG_E("Failed to create key scan thread");
    }

    auto_start_onenet();

    while (1)
    {
        rt_thread_mdelay(10000);
        LOG_I("Main thread running... WiFi status: %s", wifi_connected ? "Connected" : "Disconnected");
    }

    return 0;
}
